
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.*;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.xml.sax.SAXException;

public class DebugXmlRpcClient extends XmlRpcClient{

	@Override
	public void setConfig(XmlRpcClientConfig pConfig) {
		super.setConfig(pConfig);
		final XmlRpcClient self = this;
		final XmlRpcTransportFactory transportFactory = new XmlRpcTransportFactory()
		{
			@Override
			public XmlRpcTransport getTransport()
			{
				return new MessageLoggingTransport(self);
			}
		};
		super.setTransportFactory(transportFactory);
	}
	private class MessageLoggingTransport extends XmlRpcSunHttpTransport {
	public MessageLoggingTransport(XmlRpcClient client) {
		super(client);
	}
	
	/**
	 * Записать в лог запрос клиента
	 * @param pWriter
	 * @throws XmlRpcException 
	 */
    @Override
    protected void writeRequest(XmlRpcStreamTransport.ReqWriter pWriter) throws XmlRpcException
    {
		try {
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
			pWriter.write(baos);
			Log.log("SEND XML: " + baos.toString(), Log.DEBUG);
			super.writeRequest(pWriter);
		} catch (IOException ex) {
			Logger.getLogger(MessageLoggingTransport.class.getName()).log(Level.SEVERE, null, ex);
		} catch (SAXException ex) {
			Logger.getLogger(MessageLoggingTransport.class.getName()).log(Level.SEVERE, null, ex);
		}
    }


    /**
	 * Записать в лог ответ сервера
	 * 
	 * @param pConfig
	 * @param pStream
	 * @return
	 * @throws XmlRpcException 
	 */
    @Override
    protected Object readResponse(XmlRpcStreamRequestConfig pConfig, InputStream pStream) throws XmlRpcException
    {
		final StringBuffer sb = new StringBuffer();

        try
        {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(pStream));
            String line = reader.readLine();
            while(line != null)
            {
                sb.append(line);
                line = reader.readLine();
            }
        }
        catch(final IOException e) {
        }
		Log.log("RECV XML: "+sb.toString(), Log.DEBUG);
        final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
        return super.readResponse(pConfig, bais);
    }
}
	
}
